package com.mogu.biguser.common.filter;

import com.mogu.biguser.common.constant.AuthConst;
import com.mogu.biguser.common.util.HTTPUtil;
import com.mogu.biguser.common.util.SessionStorage;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;


/**
 * 客户端登录filter
 */

public class LoginFilter implements Filter {
    private FilterConfig config;

    @Override
    public void destroy() {
    }


    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession();
        String uri = request.getRequestURI();
        String backUrl = "";
        if (session.getAttribute(AuthConst.IS_LOGIN) != null) {
            chain.doFilter(req, res);
            return;
        }
        //String tokenapp = request.getParameter(AuthConst.APPTOKEN);
        String sessionId = session.getId();
        System.out.println(sessionId + "lanjie");
        String tokenapp = request.getHeader("x-auth-token");
        System.out.println(tokenapp + "lanjie");

        if (tokenapp != null) {    //去认证中心效验

            session.setAttribute(AuthConst.IS_LOGIN, true);
            session.setAttribute(AuthConst.APPTOKEN, tokenapp);

            //session.setMaxInactiveInterval(480 * 60);
            // 存储，用于注销
            SessionStorage.INSTANCE.set(tokenapp, session);
            SessionStorage.INSTANCE.set2("token", tokenapp);
            chain.doFilter(req, res);
            return;
        }


        // js css png jpg等文件放行
        if (uri.contains(".png") || uri.contains(".js") || uri.contains(".css") || uri.contains(".jpg") || uri.contains(".woff2") || uri.contains(".woff") || uri.contains(".ttf") || uri.contains(".ico")) {
            chain.doFilter(req, res);
            return;
        }

        // 被动注销，即从认证中心发送的注销请求
        String token2 = request.getParameter(AuthConst.LOGOUT_REQUEST);
        if (token2 != null && !"".equals(token2)) {
            session = SessionStorage.INSTANCE.get(token2);
            //SessionStorage.INSTANCE.re("token");
            if (session != null) {
                session.invalidate();
            }
            chain.doFilter(req, res);
            return;
        }

        // 建立局部会话，证明已经登录，放行
        if (session.getAttribute(AuthConst.IS_LOGIN) != null) {
            chain.doFilter(req, res);
            return;

        }

        // 从认证中心回跳的带有token的请求，有效则放行
        String token = request.getParameter(AuthConst.TOKEN);
        Map<String, String> params = new HashMap<String, String>();
        if (token != null) {    //去认证中心效验
            params.put(AuthConst.TOKEN, token);
            boolean result2 = HTTPUtil.post("http://192.168.101.10:8080/BasePlatForm/check", params);
            if (!result2) {
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                PrintWriter out = null;
                try {
                    out = response.getWriter();
                    backUrl = config.getInitParameter(AuthConst.LOGIN_URL) + "?" + AuthConst.CLIENT_URL + "=";

                    out.append("{\"code\": -2,\"data\":\"" + backUrl + "\",\"msg\":\"notlogin\"}");
                } catch (IOException e) {
//		        e.printStackTrace();
                } finally {
                    if (out != null) {
                        out.close();
                    }
                }
                return;
            }

            session.setAttribute(AuthConst.IS_LOGIN, true);
            session.setAttribute(AuthConst.TOKEN, token);
            session.setMaxInactiveInterval(480 * 60);
            // 存储，用于注销
            SessionStorage.INSTANCE.set(token, session);
            SessionStorage.INSTANCE.set2("token", token);
            chain.doFilter(req, res);
            return;
        }


        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            backUrl = config.getInitParameter(AuthConst.LOGIN_URL) + "?" + AuthConst.CLIENT_URL + "=";

            out.append("{\"code\": -2,\"data\":\"" + backUrl + "\",\"msg\":\"notlogin\"}");
        } catch (IOException e) {
//		        e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return;
    }


    /*   */


    public void init(FilterConfig filterConfig) throws ServletException {
        config = filterConfig;
    }

}